<?php
Zend::loadClass('Lead_EDO_Datatype_Relation');

class Lead_EDO_Datatype_Relation_HasMany extends Lead_EDO_Datatype_Relation
{

   	private $_className;
   	   	
   	private $_value;
   	
   	private $_options = array();
   	
   	private $_keys;
   	
    public function __construct(Lead_EDO_Object_Abstract $owner, $config = array())
	{
		parent::__construct($owner, $config);	

		$this->_foreignKey = (isset($config['foreign_key'])) ? $config['foreign_key'] : $this->getOwner()->getClass() . '_id';
		$this->_className = $config['class_name'];
		$this->getOwner()->attach($this, 'afterFetch', '_afterFetchActions');
        $this->getOwner()->attach($this, 'onSaveSuccess', '_save');
        $this->getOwner()->attach($this, 'onInsertSuccess', '_save');
		
	}
	
	
   	public function getOptions()
	{
   	    	    
	    if(!isset(EDO::$relationOptions[$this->getOwner()->getClass()][$this->getName()]))
	    {
	       $args = $this->parseConditionsToValues();
	      
           $obj = $this->getOwner()->getHandler()->get($this->getClassName());
	       
           
           
           
           if($this->getConfig('order'))
           {
               $obj->getFinder()->addOrderer($this->getConfig('order'));
           }
           
           $query = $obj->getFinder()->getQuery();
                                 
           $display = $this->getConfig('display');
           $regexp = "/(\%([a-zA-Z_]*))/si";
           preg_match_all($regexp, $display, $fields);
           $fields = $fields[2];
           $fields = array_unique($fields);
           foreach($fields as $field)
           {
               $table = $obj->getFieldsTable($field);
               
               $query->addField("{$table}.{$field}", false);
                                             
               if(!$query->tableIsJoined($table))
                    $query->addJoin($table, 'INNER', "edo.id = {$table}.id");
           }
          
           $result = $query->ldb->getAll($query->getSQL());
           
          
           
           $opzions = array();
           foreach($result as $row)
           {
               $display2 = $display;
               foreach($fields as $field)
               {
                    $display2 = str_ireplace("%{$field}", $row[$field], $display2);
               }
               $opzions[$row['id']] = $display2;
           }

           
           
           /*
           $options = $obj->getFinder()->findAll($args, false, 'fast2');
	       $opzions = array();
           foreach($options as $obj)
	       {
	          $opzions[$obj->id] = $this->resolveTags($obj, $this->getConfig('display'));
	       }
           */
	       EDO::$relationOptions[$this->getOwner()->getClass()][$this->getName()] = $opzions;
	       
	    }
	    
	    return EDO::$relationOptions[$this->getOwner()->getClass()][$this->getName()];

   
	    
	}

	
	
	
	
	public function _afterFetchActions()
	{
	}
	
	
	public function getValue()
	{
		/* @var $obj EDO_Object_basic */
	    $obj = $this->getOwner()->edo->get($this->_className);
	    	    	    
	    if($this->getOrder())
	       $obj->getFinder()->addOrderer($this->getOrder());
	    
	    $coll = $obj->getFinder()->findAll(array(array($this->getForeignKey(), '=', $this->getOwner()->id)));	    
	    
	    return $coll;
	    
	    
	    // return $this->_value;
	    
	}
	
	
	
	public function setValue($value, $validate = true)
    {
        if($validate)
            $value = $this->validate($value);
                
        if(is_array($value))
        {
            
            $this->_keys = $value;
            return true;
        }
        
        return ($value === false) ? false : true;
        
    }
    
    
    public function getDefaultValue()
    {
        return array();
    }
    
    
    public function validate($value)
    {
                
        if(!is_array($value))
        {
            $value = explode(',', $value);
            foreach($value as $key => &$valRef)
            {
                $valRef = trim($valRef);
            }
                
        }
        
        if(isset($value['faker']))
        {
            $value = (isset($value['values'])) ? $value['values'] : array();
        }

               
        $options = $this->getOptions();

        
        $validated = array();
        foreach($value as $key => &$valRef)
        {
            if(key_exists($valRef, $options))
            {
                $validated[] = $valRef;
            }
            elseif($theKey = array_search($valRef, $options))
            {
                $validated[] = $theKey;
            }
        }
        return $validated;
    }

	
	
	public function joinTo(Query $query)
	{
        $args = $this->parseConditionsToTables();
      
        $obj = $this->getOwner()->edo->get($this->_className);
        $tables = $obj->getTables();
        
        $fKeyTable = $obj->getFieldObject($this->getForeignKey())->getTable();
        
        $firstTable = array_shift($tables);
        $query->addJoin($firstTable, 'INNER', "{$fKeyTable}.{$this->getForeignKey()} = {$this->getOwner()->getFirstTable()}.id");
        
        foreach($tables as $table)
        {
            $query->addJoin($table, 'INNER', "{$firstTable}.id = {$table}.id");
        }
       
       
	        
	}
	

    public function getOpposite()
    {
  	   $obj = $this->getOwner()->edo->get($this->getClassName());
         	     	   
  	   foreach($obj->getRelationObjects() as $relObj) 
       {
           if($relObj->getForeignKey() == $this->getForeignKey())
            return $obj->getClass() . '_' . $relObj->getName();
       }

    }
    
    
    
    public function _save()
    {
                      
        if(!is_null($this->_keys))
        {
       	    $coll = $this->getValue();
       	    foreach($coll as $item)
       	    {
       	        if(!in_array($item->id, $this->_keys))
       	        {
       	            $item->setField($this->getForeignKey(), null);
       	            $item->save();
       	        }
       	    }
            
            
            
            $obj = $this->getOwner()->edo->get($this->_className);
       	    $coll = $obj->collection();
       	    
       	    $coll->setItems($this->_keys);
            
            foreach($coll as $key => $item)            
            {
                if(!in_array($item->id, $this->_keys))
                {
                    $item->setField($this->getForeignKey(), null);
                    $item->save();
                }
                else 
                {
                    if($item->getField($this->getForeignKey()) != $this->getOwner()->id)
                    {
                        $item->setField($this->getForeignKey(), $this->getOwner()->id);
                        $item->save();
                    }
                }
                
                
            }

            
        }
        
        
         
        return true;           
    }
    

	
}